import Vue from 'vue'
import Router from 'vue-router'

import { asyncRoutes, constantRoutes } from '@/router'

import { authmenulist } from '@/api/user'// 【新加入】引入请求，获得权限菜单

import Layout from '@/layout'// 【新加入】引入layout

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export function generaMenu(routes, data) {

  data.forEach(item => {

    //path不为空的话，就新建一个对象，装数据
    if (item.path !== '') {
      //这个就仿照目录的机构，搭建
      const menu = {
        path: item.path,
        component: Layout, //这个不用写data里面的内容，引用就行了
        redirect: item.redirect,
        children: [],
        name: item.name,
        meta: item.meta,
      }

      //遍历子标签，并加入到主目录的children中去
      item.children.forEach(item2 => {

        var meta3_new = {
            title: item2.meta.title,
            noCache: false,
            name: item2.meta.name,
        };

        var cate = item2.cate;
        if (cate == 2) {
          var xs = true;
        } else {
          var xs = item2.hidden;
        }

        var a = item2.component;
        var menu2 = {
          path: item2.path,
          component:  (resolve) => require(['@/views' + a], resolve),
          name: item2.meta.name,
          meta: meta3_new,
          hidden: xs,
          children: [],
        }

        if (item2.children != undefined) {

          item2.children.forEach(item3 => {
            //console.log(item3)
            var meta4_new = {
                title: item3.meta.title,
                noCache: false,
                name: item3.meta.name,
            };

            var b = item3.component;
            var menu3 = {
              path: item3.path,
              component: (resolve) => require(['@/views' + b], resolve),
              name: item3.meta.name,
              meta: meta4_new,
              hidden: item3.hidden,
            }
            //console.log(menu3);
            menu2.children.push(menu3)
           })
        }



        //加入到主目录的children中去
        menu.children.push(menu2)
      })


      //追加
      routes.push(menu)

      console.log(menu)
    }
  })
  //把404加到最后，因为作者说  // 404 page must be placed at the end !!!
  const menu3 = {
    path: '*',
    redirect: '/404',
    hidden: true
  }
  //追加
  //routes.push(menu3)
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 【新加入】开始
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由，authMenu（state.token）后面会写
      authmenulist().then(response => {
        if (response.code !== 200) {
          //console.log("ddd");
        } else {
            //获取目录的json
          let data = response.response
            //把data的数据拷贝到loadMenuData里面
          Object.assign(loadMenuData, data)
            //把asyncRoutes的数据拷贝到tempAsyncRoutes里面
          const tempAsyncRoutes = Object.assign([], asyncRoutes)
          // 最最重要的，把loadMenuData追加到tempAsyncRoutes后面
          generaMenu(tempAsyncRoutes, data)
            //定义accessedRoutes
          let accessedRoutes
          // 把 tempAsyncRoutes 的值给 accessedRoutes ，并输出
          // eslint-disable-next-line prefer-const
          accessedRoutes = tempAsyncRoutes || []
            //下面这些就是加载目录了
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
      })
    }).catch(error => {
      console.log(error)
    })
  }
}

/*const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}*/

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
